package com.example.yan_music.adapter;

import android.content.Context;
import android.graphics.Rect;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.example.yan_music.R;
import com.example.yan_music.bean.wangyi.NewSearchSong;
import com.example.yan_music.db.table.FavoriteSong;
import com.example.yan_music.listener.OnRcvClickListener;
import com.example.yan_music.utils.DipAndPxUtils;
import com.example.yan_music.utils.TextFontUtils;
import com.example.yan_music.utils.XToast;
import com.example.yan_music.widge.dialog.XDialog;

import org.litepal.LitePal;

import java.util.List;

/**
 * <p>
 *      搜索页面 RecyclerView 的适配器
 * </p>
 */
public class RcvSearchAdapter extends RecyclerView.Adapter<RcvSearchAdapter.MyHolder> {

    private static final String TAG = "RcvSearchAdapter";

    private OnRcvClickListener mItemClicklistener;

    private OnSelectItemListener mItemSelectListener;

    private final Context mContext;

    /**
     * 数据源，搜索到的歌曲列表
     */
    private List<NewSearchSong.ResultBean.SongsBean> mSearchList;

    /**
     * 用户输入的字段（需要高亮的字段）
     */
    private String mInputKeywords;

    /**
     * 构造器
     *
     * @param inputKeywords 用户在搜索页面输入的关键词
     */
    public RcvSearchAdapter(List<NewSearchSong.ResultBean.SongsBean> mSearchList, String inputKeywords, Context context) {
        this.mContext = context;
        this.mSearchList = mSearchList;
        this.mInputKeywords = inputKeywords;
    }

    /**
     * “更多选项”弹窗
     */
    private PopupWindow mPopWindow;
    private LinearLayout ll_add, ll_todo, ll_detail;

    private XDialog xDialog;

    /**
     * 高亮颜色
     */
    private String mHighlightColor1 = "#33CC99";
    private String mHighlightColor2 = "#FFFF00";

    @NonNull
    @Override
    public MyHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = View.inflate(parent.getContext(), R.layout.rcv_search_item, null);
        return new MyHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull MyHolder holder, int position) {
        //Logger.d(position);
        holder.setData(mSearchList.get(position), position);
        holder.setIsRecyclable(false);
        mItemSelectListener.convert(holder, position);
    }


    /**
     * 获取列表子项个数
     *
     * @return
     */
    @Override
    public int getItemCount() {
        if (mSearchList != null) {
            return mSearchList.size();
        }
        return 0;
    }

    /**
     * ViewHolder
     */
    public class MyHolder extends RecyclerView.ViewHolder {
        private TextView tv_song_name, tv_singer_name;
        private ImageView img_love, img_more;
        private RelativeLayout rl_rcv_item;
        private View contentViewOfWindow;

        /**
         * 当前子项位置
         */
        private int position;

        /**
         * 具体解析的字段
         */
        private String songName; // 歌曲名
        private String singerName;  // 歌手名
        private String songMid; // 歌曲id

        public MyHolder(@NonNull final View view) {
            super(view);
            contentViewOfWindow = LayoutInflater.from(view.getContext()).inflate(R.layout.layout_item_menu, null);
            tv_song_name = view.findViewById(R.id.tv_search_song_name);
            tv_singer_name = view.findViewById(R.id.tv_singer_name);
            img_love = view.findViewById(R.id.img_love);
            img_more = view.findViewById(R.id.img_more);
            rl_rcv_item = view.findViewById(R.id.rcv_item);

            img_love.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    addSongToFavorite(songMid);
                    Log.d(TAG, "onClick: " + "songId = " + songMid);
                }
            });

            img_more.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    showPopupWindow(mContext, v, position);
                }
            });

            rl_rcv_item.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    mItemClicklistener.onItemClick(v, position);
                }
            });

        }

        /**
         * 初始化数据
         *
         * @param listBean   数据源
         * @param position   当前位置
         */
        public void setData(NewSearchSong.ResultBean.SongsBean listBean, int position) {
            // 初始化位置
            this.position = position;
            // 歌曲名
            songName = listBean.getName();
            // 歌手名
            singerName = listBean.getArtists().get(0).getName();
            // 歌曲标识符
            songMid = "" + listBean.getId() + "";

            // 高亮显示 <歌曲名>
            TextFontUtils.setHighlightFont(mInputKeywords, songName, tv_song_name, mHighlightColor1);
            // 高亮显示 <歌手>
            TextFontUtils.setHighlightFont(mInputKeywords, singerName, tv_singer_name, mHighlightColor2);

            // 这里判断一下是否被收藏了，列表展示的时候，爱心不会随着item移除视野而自动变灰
            if(LitePal.where("songMid = ?", songMid).find(FavoriteSong.class).isEmpty()){
                img_love.setImageResource(R.drawable.xihaun2);
            }else {
                img_love.setImageResource(R.drawable.xihaun_1);
            }
        }

        /**
         * 将标记为收藏的歌曲添加到FavoriteSong表中
         *
         * @param songMid 歌曲的id
         */
        public void addSongToFavorite(final String songMid) {
            Log.d(TAG, "addSongToFavorite:  "
                    + "\n 点击位置为：" + position
                    + "\n 该位置歌曲为："
                    + "\n {[ \n   "
                    + songMid
                    + "\n   " + songName
                    + "\n   " + singerName
                    + "\n]}");
            // 查询集
            List<FavoriteSong> queryList = LitePal.where("songMid = ?", songMid).find(FavoriteSong.class);
            Log.d(TAG, "addSongToFavorite: " + "查询集大小：" + queryList.size());
            // 根据查询结果列表是否为空来判断收藏与否
            if (queryList.isEmpty()) {
                // 查询集为空表示该歌曲没有被收藏，这时收藏
                FavoriteSong mFSong = new FavoriteSong();
                mFSong.setSongName(songName);
                mFSong.setSingerName(singerName);
                mFSong.setSongMid(songMid);
                mFSong.setFavorite(true);
                mFSong.save();
                Log.d(TAG, "addSongToFavorite: " + "该歌曲是否收藏： " + mFSong.isFavorite());
                // 点亮爱心
                img_love.setImageResource(R.drawable.xihaun_1);
                XToast.showSucceed("收藏成功");
                Log.d(TAG, "addSongToFavorite: " + mFSong.getSongName() + "收藏成功！");
            } else {
                FavoriteSong mFSong = queryList.get(0);
                if (mFSong.isFavorite()) {
                    showCancelFavoriteDialog(songMid, mFSong);
                } else {
                    // 将该歌曲从表中删除
                    LitePal.deleteAll(FavoriteSong.class, "songMid = ?", songMid);
                    // 熄灭爱心
                    img_love.setImageResource(R.drawable.xihaun2);
                    XToast.showWarning("取消收藏");
                }
            }
        }

        /**
         * 取消收藏的dialog
         * @param songMid
         * @param mFSong
         */
        private void showCancelFavoriteDialog(final String songMid, FavoriteSong mFSong) {
            xDialog = new XDialog.XBuilder(mContext)
                  .setIcon(R.drawable.jingao_huangse)
                  .setPositiveTextColor(mContext.getResources().getColor(R.color.huangse))
                  .setTitleTextColor(mContext.getResources().getColor(R.color.huangse))
                  .setTitle("取消")
                  .setMessage("《" + mFSong.getSongName() + "》已经被收藏了，确定取消收藏吗？")
                  .setPositiveListener("确认", new View.OnClickListener() {
                      @Override
                      public void onClick(View v) {
                          LitePal.deleteAll(FavoriteSong.class, "songMid = ?", songMid);
                          // 熄灭爱心
                          img_love.setImageResource(R.drawable.xihaun2);
                          XToast.showWarning("取消收藏");
                          Log.d(TAG, "onClick: "
                                          + "\n 歌曲[ " + songName + " ]被取消收藏");
                          xDialog.dismiss();
                      }
                  })
                  .setNegativeListener("我再想想", new View.OnClickListener() {
                      @Override
                      public void onClick(View v) {
                          xDialog.dismiss();
                      }
                  })
                  .create(XDialog.XType.CONFIRM);
            xDialog.show();
        }

        /**
         * 显示菜单
         *
         * @param context
         * @param targetView
         * @param position    子项所在位置，通过位置获取该子项的歌曲信息，从list.get(position)获取
         */
        public void showPopupWindow(Context context, View targetView, int position) {
            View contentViewOfWindow = LayoutInflater.from(targetView.getContext()).inflate(R.layout.layout_item_menu, null);
            ll_add = contentViewOfWindow.findViewById(R.id.ll_add);
            ll_detail = contentViewOfWindow.findViewById(R.id.ll_detail);
            ll_todo = contentViewOfWindow.findViewById(R.id.ll_todo);
            ll_add.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    // TODO 点击完后将指定歌曲添加到某个歌单中
                    mPopWindow.dismiss();
                }
            });
            ll_detail.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    // TODO 歌曲细节
                    mPopWindow.dismiss();
                }
            });
            ll_todo.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    // TODO 其他功能
                    mPopWindow.dismiss();
                }
            });
            // 显示弹窗布局
            mPopWindow = new PopupWindow(contentViewOfWindow, DipAndPxUtils.dip2px(context, 130), DipAndPxUtils.dip2px(context, 150));
            // 设置焦点
            mPopWindow.setFocusable(true);
            // 设置可以触摸弹窗以外的地方
            mPopWindow.setOutsideTouchable(false);
            // 给弹窗设置 弹出和收起动画
            mPopWindow.setAnimationStyle(R.style.popupwindow_anim);
            // 更新弹出窗口的尺寸。调用此函数还将更新窗口，使其具有当前弹出状态
            mPopWindow.update();
            // 在指定位置弹出，右偏300px，下偏20px
            mPopWindow.showAsDropDown(targetView, -300, 20);
        }
    }

    /**
     * 用来调节Item之间的间距的装饰类
     */
    public static class ItemSpaceDecoration extends RecyclerView.ItemDecoration {
        // item 之间的间距
        private int left;
        private int right;
        private int top;
        private int bottom;

        public ItemSpaceDecoration(int left, int right, int top, int bottom) {
            this.left = left;
            this.right = right;
            this.top = top;
            this.bottom = bottom;
        }

        /**
         * 设置间距
         *
         * @param outRect
         * @param view
         * @param parent
         * @param state
         */
        @Override
        public void getItemOffsets(@NonNull Rect outRect, @NonNull View view, @NonNull RecyclerView parent, @NonNull RecyclerView.State state) {
                outRect.left = left;
                outRect.right = right;
                outRect.top = top;
                outRect.bottom = bottom;

        }
    }

    /**
     * 设置子项点击监听
     * @param listener
     */
    public void setRcvClickListener(OnRcvClickListener listener){
        this.mItemClicklistener = listener;
    }

    /**
     * 子项被选中监听接口
     */
    public interface OnSelectItemListener{
        // 用于设置子项背景
        void convert(MyHolder holder, int position);
    }

    /**
     * 设置子项选中接口监听
     * @param listener
     */
    public void setOnSelectItemListener(OnSelectItemListener listener){
        this.mItemSelectListener = listener;
    }

}
